<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of dataText
 *
 * @author Alex
 */
abstract class editorField {
    protected $label, $fieldName, $explanation, $disabled, $databaseField=true;

    //renders the editor for this field.
    abstract protected function renderEditor($skin_dir, $value, $new = false);
    //validates the data passed through POST etc
    abstract protected function validateValue($value);
    //returns a query friendly value
    abstract protected function getQueryValue($value);
    //any post processing that is required after we have all data before render
    abstract protected function postProcess($data, $idfield, $titlefield);

    public function getLabel()
    {
        return $this->label;
    }

    public function getFieldName()
    {
        return $this->fieldName;
    }

    public function getExplanation()
    {
        return $this->explanation;
    }

    public function isDatabaseField()
    {
        return $this->databaseField;
    }
}


class fieldText extends editorField {

    protected $charLimit;

    public function fieldText($label, $fieldName, $explanation, $limit=0)
    {
        $this->label = $label;
        $this->fieldName = $fieldName;
        $this->explanation = $explanation;
        $this->setCharLimit($limit);
        $this->disabled = '';
    }

    public function getQueryValue($value)
    {
        $this->validateValue($value);
        return "'" . $value . "'";
    }

    public function validateValue($value, $id = '', $data = Array())
    {
        if(strlen($value) > $this->charLimit)
            throw new Exception("The entered text '" . $value . "' for the field '" . $this->label . "' was over the allowed limit of " . $this->charLimit);

        return $value;
    }

    public function postProcess($data, $idfield, $titlefield)
    {

    }

    protected function setCharLimit($limit)
    {
        if(is_numeric($limit))
            $this->charLimit = $limit;
        else
            throw new Exception("Attempted to set Char Limit to non numeric value: '" . $limit . "' in column " . $this->label);

    }

    public function renderEditor($skin_dir, $value, $new = false)
    {
        $label = $this->label;
        $charLimit = $this->charLimit;
        $fieldName = $this->fieldName;
        $explanation = $this->explanation == '' ? $this->label : $this->explanation;

        $disabled = $this->disabled;

        include $skin_dir . 'admin/fieldText.tpl';
    }
}

class fieldLongText extends fieldText {

    protected $rows;

    public function fieldLongText($label, $fieldName, $explanation, $rows=6)
    {
        $this->fieldText($label, $fieldName, $explanation, 0);
        $this->rows = $rows;
    }

    public function validateValue($value, $id = '', $data = Array())
    {
        return $value;
    }

    public function renderEditor($skin_dir, $value, $new = false)
    {
        $value = formatFormOutput($value);
        $label = $this->label;
        $fieldName = $this->fieldName;
        $explanation = $this->explanation == '' ? $this->label : $this->explanation;
        $rows = $this->rows;

        $disabled = $this->disabled;

        include $skin_dir . 'admin/fieldLongText.tpl';
    }
}


class fieldTitle extends fieldText {
    public function fieldTitle($label, $fieldName, $explanation, $limit)
    {
        $this->fieldText($label, $fieldName, $explanation, $limit);
    }
}

class fieldNumeric extends fieldText {

    protected $limitNumbers, $minLimit, $maxLimit;


    public function fieldNumeric($label, $fieldName, $explanation, $minLimit = null, $maxLimit = null)
    {

        $charLimit = 0;

        if(is_null($minLimit) && is_null($maxLimit) )
            $this->limitNumbers = false;
        elseif(is_numeric($minLimit) && is_numeric($maxLimit) && $minLimit <= $maxLimit)
        {
            global $lang;

            $this->limitNumbers = true;
            $this->minLimit = $minLimit;
            $this->maxLimit = $maxLimit;
            $charLimit = strlen('' . $maxLimit);
            $explanation .= $explanation == '' ? '': '<br/>';
            $explanation .= sprintf($lang['FieldNumericHint'], $minLimit, $maxLimit);
        }
        else
        {
            $this->limitNumbers = false;
            throw new Exception("Attempted to set invalid numeric limits from: '" . $minLimit . "' to '" . $maxLimit . "' in column " . $this->label);
        }

        $this->fieldText($label, $fieldName, $explanation, $charLimit);


    }

    public function getQueryValue($value)
    {
        $this->validateValue($value);
        return $value;
    }

    public function validateValue($value, $id = '', $data = Array())
    {
        if (! is_numeric($value))
            throw new Exception("Attempt to enter non numeric value '" . $value . "' for the field :" . $this->label);
        elseif($this->limitNumbers && ($value > $this->maxLimit || $value < $this->minLimit))
            throw new Exception("The number '" . $value . "' for the field '" . $this->label . "' was outside the numeric limits of " . $this->minLimit . " and " . $this->maxLimit);

        return $value;
    }
}


class fieldId extends fieldNumeric {


    public function fieldId($fieldName)
    {
        $this->fieldNumeric("", $fieldName, "");
    }

    public function renderEditor($skin_dir, $value, $new = false)
    {
        $fieldName = $this->fieldName;

        include $skin_dir . 'admin/fieldId.tpl';
    }
}

//dummy field that is not shown and has it's values controlled by another field.
class fieldDummy extends editorField
{
    protected $value = null, $queryValue = null;

    public function fieldDummy($fieldName)
    {
        $this->fieldName = $fieldName;
    }

    public function setValue($value)
    {
        $this->value = $value;
    }

    public function postProcess($data, $idfield, $titlefield)
    {
    }

    public function setQueryValue($queryValue)
    {
        $this->queryValue = $queryValue;
    }

    public function getQueryValue($value)
    {
        return is_null($this->queryValue) ? "'" . $value . "'" : $this->queryValue;
    }

    public function validateValue($value, $id = '', $data = Array())
    {
        return is_null($this->value) ? $value : $this->value;
    }


    public function renderEditor($skin_dir, $value, $new = false)
    {
        $fieldName = $this->fieldName;

        include $skin_dir . 'admin/fieldHidden.tpl';
    }
}

//basic file upload
class fieldFile extends fieldText {

    protected $incomingFileName;
    protected $filenamePrefix;
    protected $newFilename = null;

    public function fieldFile($label, $fieldName, $explanation, $filenamePrefix)
    {
        $this->fieldText($label, $fieldName, $explanation);

        $this->incomingFileName = $fieldName . 'NewFile';
        $this->filenamePrefix = $filenamePrefix;
    }

    public function getQueryValue($value)
    {
        $value = $this->validateValue($value);
        
        return $value == '' ? $value : "'" . $value . "'";
    }

    public function validateValue($value , $id = '', $data = Array())
    {
        if($id != '')
        {
            $this->processUploadedFile($data[$id]);
        }
        return is_null($this->newFilename) ? $value : $this->newFilename;
    }

    protected function processUploadedFile($idvalue)
    {
        print_r ($_FILES);
        
        if(isset($_FILES[$this->incomingFileName]))
        {
            global $properties, $lang;

            //current filename info
            $currentFile = pathinfo($_FILES[$this->incomingFileName]["name"] );

            //generate the file name
            $this->newFilename = $properties['file_upload_dir'] . $this->filenamePrefix . $idvalue . "." . $currentFile['extension'] ;

            move_uploaded_file($_FILES[$this->incomingFileName]["tmp_name"], $this->newFilename);

            //prevent from running this again
            unset($_POST[$this->incomingFileName]);
        }
    }

    public function renderEditor($skin_dir, $value, $new = false)
    {
        global $properties;
        
        $label = $this->label;
        $fieldName = $this->fieldName;
        $newFile = $this->incomingFileName;
        $explanation = $this->explanation == '' ? $this->label : $this->explanation;
        $maxfilesize = $properties['max_upload_filesize'];

        $disabled = $new ? 'disabled' : '';

        include $skin_dir . 'admin/fieldFile.tpl';
    }
}

//image upload
class fieldImage extends fieldText {

    protected $incomingFileName;
    protected $filenamePrefix;
    protected $newFilename = null;

    protected $imageWidth, $imageHeight, $generateThumbnail, $thumbDummyObject,
            $thumbWidth, $thumbHeight, $cropToHeight;


    public function fieldImage($label, $fieldName, $explanation, $filenamePrefix, $imageWidth, $imageHeight, $cropToHeight = true,
            $generateThumbnail = false, $thumbDummyObject = null, $thumbWidth = 0, $thumbHeight = 0)
    {
        $this->fieldText($label, $fieldName, $explanation);

        $this->incomingFileName = $fieldName . 'NewFile';
        $this->filenamePrefix = $filenamePrefix;

        $this->imageHeight = $imageHeight;
        $this->imageWidth = $imageWidth;
        $this->cropToHeight = $cropToHeight;

        $this->generateThumbnail = $generateThumbnail;
        $this->thumbDummyObject = $thumbDummyObject;
        $this->thumbWidth = $thumbWidth;
        $this->thumbHeight = $thumbHeight;
    }

    public function getQueryValue($value)
    {
        $value = $this->validateValue($value);

        return "'" . $value . "'";
    }

    public function validateValue($value , $id = '', $data = Array())
    {
        if($id != '')
        {
            $this->processUploadedFile($data[$id]);
        }
        return is_null($this->newFilename) ? $value : $this->newFilename;
    }

    protected function processUploadedFile($idvalue)
    {
        if(isset($_FILES[$this->incomingFileName]) && $_FILES[$this->incomingFileName]['error'] != UPLOAD_ERR_NO_FILE)
        {


            global $properties, $lang;


            $image = 0;
            if( ($_FILES[$this->incomingFileName]['type']=="image/gif") ) {
                 $image = imagecreatefromgif($_FILES[$this->incomingFileName]['tmp_name']);
            }
            elseif($_FILES[$this->incomingFileName]['type']=="image/jpeg" || $_FILES['uploadedfile']['type']=="image/pjpeg" ) {
                 $image = imagecreatefromjpeg($_FILES[$this->incomingFileName]['tmp_name']);
            }
            elseif( $_FILES[$this->incomingFileName]['type']=="image/png") {
                 $image = imagecreatefrompng($_FILES[$this->incomingFileName]['tmp_name']);
            }
            else
            {
                 throw new Exception($lang['LogoError']);
            }

            //current filename info
            $currentFile = pathinfo($_FILES[$this->incomingFileName]["name"] );

            //generate the file name
            $this->newFilename = $properties['file_upload_dir'] . $this->filenamePrefix . $idvalue . ".jpg";


            //resize and crop our image
            $image = cropImage($this->imageWidth, $this->imageHeight, $image, $this->cropToHeight);

            if(imagejpeg($image,$this->newFilename,95) )
            {
                    $thmburl = '';
                    $thmbimage = '';
                    if($this->generateThumbnail)
                    {
                            $thmbimage = cropImage($this->thumbWidth, $this->thumbHeight, $image, $this->cropToHeight);
                            $thmburl = $properties['file_upload_dir'] . $this->filenamePrefix  . $idvalue . "_thmb.jpg";
                            if(imagejpeg($thmbimage,$thmburl,90) )
                            {
                                 $this->thumbDummyObject->setValue($thmburl);
                                 $this->thumbDummyObject->setQueryValue("'" . $thmburl . "'");
                            }
                            else
                            {
                                throw new Exception($lang['LogoError']);
                            }
                    }
            }
            else
            {
                throw new Exception($lang['LogoError']);
            }

            //prevent from running this again
            unset($_POST[$this->incomingFileName]);
        }
    }

    public function renderEditor($skin_dir, $value, $new = false)
    {
        global $properties, $lang;

        $label = $this->label;
        $fieldName = $this->fieldName;
        $newFile = $this->incomingFileName;
        $explanation = $this->explanation == '' ? $this->label : $this->explanation;
        $maxfilesize = $properties['max_upload_filesize'];
        $currentimage = $value == '' ? $lang['NoLogo'] :
				'<img src="' . $value . '"/>';

        $uploadImageInfo  = sprintf($lang['LogoFilesize'],$this->imageWidth, $this->imageHeight);
        if($this->generateThumbnail)
        {
            $uploadImageInfo .= ' ' . sprintf($lang['LogoThumbnailInfo'],$this->thumbWidth, $this->thumbHeight);
        }

        if($this->generateThumbnail && $value != '')
        {
            $thumbparts = pathinfo($value);
            $currentimage = '<img src="' . $thumbparts['dirname'] . '/' . $thumbparts['filename'] .
                            '_thmb.' . $thumbparts['extension']. '"/><BR/><BR/>' . $currentimage;
            
        }
        $disabled = $new ? 'disabled' : '';

        include $skin_dir . 'admin/fieldImage.tpl';
    }
}



class fieldSimpleComboBox extends editorField {

    protected $data;

    public function fieldSimpleComboBox($label, $fieldName, $explanation, $data)
    {
        $this->label = $label;
        $this->fieldName = $fieldName;
        $this->explanation = $explanation;
        $this->data = $data;
        $this->disabled = '';
    }

    public function getQueryValue($value)
    {
        $this->validateValue($value);
        return is_numeric($value) ? $value : "'" . $value . "'" ;
    }

    public function validateValue($value, $id = '', $data = Array())
    {
        return $value;
    }

    public function postProcess($data, $idfield, $titlefield)
    {
    }

    protected function generateComboOutput($selected)
    {
        $output = '';
        foreach($this->data as $key => $value)
        {
            $thisval = '';
            if($key == $selected)
                $thisval = ' SELECTED';

            $output.='<option value="' . $key . '"'. $thisval.'>' . $value . '</option>';
        }
        return $output;
    }

    public function renderEditor($skin_dir, $value, $new = false)
    {
        $label = $this->label;
        $fieldName = $this->fieldName;
        $explanation = $this->explanation == '' ? $this->label : $this->explanation;
        $output = $this->generateComboOutput($value);

        $disabled = $this->disabled;

        include $skin_dir . 'admin/fieldCombo.tpl';
    }
}

class fieldYesNoComboBox extends fieldSimpleComboBox {

    function fieldYesNoComboBox($label, $fieldName, $explanation)
    {
        global $lang;
        $data = Array(0=>$lang['No'], 1=>$lang['Yes']);

        $this->fieldSimpleComboBox($label, $fieldName, $explanation, $data);
    }
}


class fieldTableQueryComboBox extends fieldSimpleComboBox {

    public function fieldTableQueryComboBox($label, $fieldName, $explanation,
            $query, $columnid, $columnlabel,
            $zerovalue = false, $zeroid = 0, $zerolabel = "")
    {
        $data = $this->getData($query, $columnid, $columnlabel, $zerovalue, $zeroid, $zerolabel);
        $this->fieldSimpleComboBox($label, $fieldName, $explanation, $data);
    }

    protected function generateZeroRecord($zerovalue, $zeroid, $zerolabel)
    {
        $data = Array();
        if($zerovalue)
        {
            $data[$zeroid] = $zerolabel;
        }
        return $data;
    }


    protected function getData($query, $columnid, $columnlabel, $zerovalue, $zeroid, $zerolabel)
    {
        $data = $this->generateZeroRecord($zerovalue, $zeroid, $zerolabel);

        global $db;

        $result = $db->sql_query($query);
        while($row = $db->sql_fetchrow($result))
        {
            $data[$row[$columnid]] = $row[$columnlabel];
        }

        return $data;
    }

    protected function generateComboOutput($selected)
    {
        $output = '';
        foreach($this->data as $key => $value)
        {
            $thisval = '';
            if($key == $selected)
                $thisval = ' SELECTED';

            $output.='<option value="' . $key . '"'. $thisval.'>' . $value . '</option>';
        }
        return $output;
    }
}


class fieldRecordQueryComboBox extends fieldSimpleComboBox {

    protected  $zerodata, $query, $columnid, $columnlabel, $datagenerated=false;

    public function fieldRecordQueryComboBox($label, $fieldName, $explanation,
            $query, $columnid, $columnlabel,
            $zerovalue = false, $zeroid = 0, $zerolabel = "")
    {
        $this->query = $query;
        $this->columnid = $columnid;
        $this->columnlabel = $columnlabel;

        $this->zerodata = $this->generateZeroRecord($zerovalue, $zeroid, $zerolabel);

        $this->fieldSimpleComboBox($label, $fieldName, $explanation, $this->zerodata);
    }

    public function postProcess($data, $idfield, $titlefield)
    {
        if(!$this->datagenerated)
              $this->fillData($this->query, $this->columnid, $this->columnlabel, $idfield, $data);
    }

    protected function generateZeroRecord($zerovalue, $zeroid, $zerolabel)
    {
        $data = Array();
        if($zerovalue)
        {
            $data[$zeroid] = $zerolabel;
        }
        return $data;
    }

    protected function fillData($query, $columnid, $columnlabel, $recordidfield, $recorddata)
    {
        global $db;
        
        //update query with record id value
        $query = sprintf($query, $recorddata[$recordidfield]);

        $result = $db->sql_query($query);
        while($row = $db->sql_fetchrow($result))
        {
            $this->data[$row[$columnid]] = $row[$columnlabel];
        }

        $this->datagenerated = true;
    }

    protected function generateComboOutput($selected, $new)
    {
        $output = '';
        $data = $new ? $this->zerodata : $this->data;
        foreach($data as $key => $value)
        {
            $thisval = '';
            if($key == $selected)
                $thisval = ' SELECTED';

            $output.='<option value="' . $key . '"'. $thisval.'>' . $value . '</option>';
        }
        return $output;
    }

    public function renderEditor($skin_dir, $value, $new = false)
    {
        $label = $this->label;
        $fieldName = $this->fieldName;
        $explanation = $this->explanation == '' ? $this->label : $this->explanation;
        $output = $this->generateComboOutput($value, $new);

        $disabled = $this->disabled;

        include $skin_dir . 'admin/fieldCombo.tpl';
    }
}


class fieldInfoOnly extends editorField {

    protected $infoquery, $outputfield, $output;

    public function fieldInfoOnly($label, $fieldName, $explanation, $infoquery, $outputfield)
    {
        $this->label = $label;
        $this->fieldName = $fieldName;
        $this->explanation = $explanation;
        $this->infoquery = $infoquery;
        $this->outputfield = $outputfield;
        $this->databaseField = false;
        $this->disabled = '';
    }


    public function getQueryValue($value)
    {
        throw new Exception("Attempt to get Query Value from non database field");
    }

    public function validateValue($value)
    {
        throw new Exception("Attempt to get Validate Value from non database field");
    }

    public function postProcess($data, $idfield, $titlefield)
    {
        $this->output = '';

        if(isset($data[$idfield]) && is_numeric($data[$idfield]))
        {
            //update query with record id value
            $this->infoquery = sprintf($this->infoquery, $data[$idfield]);

            global $db;
            $result = $db->sql_query($this->infoquery);
            while($row = $db->sql_fetchrow($result))
            {
                $this->output.= $row[$this->outputfield] . '<br/>';
            }
        }
    }


    public function renderEditor($skin_dir, $value, $new = false)
    {

        $label = $this->label;

        if(!$new)
            $output = $this->output;
        else
            $output = '';
        
        $explanation = $this->explanation == '' ? $this->label : $this->explanation;

        include $skin_dir . 'admin/fieldInfo.tpl';
    }
}
?>
